package com.csun.dsms.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.csun.dsms.comment.core.annotation.Authorization;
import com.csun.dsms.comment.core.annotation.CurrentUser;
import com.csun.dsms.comment.core.support.CsunMessageSource;
import com.csun.dsms.comment.core.utils.wrapper.WrapMapper;
import com.csun.dsms.comment.core.utils.wrapper.Wrapper;
import com.csun.dsms.model.domain.*;
import com.csun.dsms.model.dto.record.RecordIdsAndEvaluation;
import com.csun.dsms.model.dto.record.RecordQueryDto;
import com.csun.dsms.model.vo.company.CompanyInfoVo;
import com.csun.dsms.model.vo.poor.PoorVo;
import com.csun.dsms.model.vo.project.ProjectVo;
import com.csun.dsms.service.DsmsAreaService;
import com.csun.dsms.service.DsmsCompanyService;
import com.csun.dsms.service.DsmsPoorService;
import com.csun.dsms.service.DsmsRecordService;
import com.csun.dsms.utils.DateUtil;
import com.csun.dsms.utils.ExportExcel;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

/**
 * @author chisj chisj@foxmail.com
 * @version 1.0.0
 * @date 2021-09-26 11:50
 * @description: 服务记录管理拦截器
 */
@RestController
@RequestMapping("/record")
public class DsmsRecordController {

    @Resource
    private CsunMessageSource csunMessageSource;
    @Resource
    private DsmsRecordService dsmsRecordService;
    @Resource
    private DsmsPoorService dsmsPoorService;
    @Resource
    private DsmsAreaService dsmsAreaService;
    @Resource
    private DsmsCompanyService dsmsCompanyService;

    /**
     * 查询服务记录列表 - 分页.
     *
     * @param recordQueryDto the record query dto
     *
     * @return the wrapper
     */
    @Authorization
    @PostMapping(value = "/queryListWithPage")
    public Wrapper queryListWithPage(@RequestBody RecordQueryDto recordQueryDto) {

        List<DsmsRecord> dsmsRecordList = dsmsRecordService.queryListWithPage(recordQueryDto);

        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, csunMessageSource
                .getMessage("operation.success", null), new PageInfo(dsmsRecordList));
    }

    /**
     * 查看服务详情.
     *
     * @param id the dsms record id
     *
     * @return the wrapper
     */
    @Authorization
    @PostMapping(value = "/showById/{id}")
    public Wrapper showById(@PathVariable Long id) {

        DsmsRecord dsmsRecord = dsmsRecordService.selectByKey(id);

        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, csunMessageSource
                .getMessage("operation.success", null), dsmsRecord);
    }

    /**
     * 根据id取消服务.
     *
     * @param id the dsms record id
     *
     * @return the wrapper
     */
    @Authorization
    @PostMapping(value = "/cancelById/{id}")
    public Wrapper cancelById(@CurrentUser DsmsUser login, @PathVariable Long id) {

        Integer result = dsmsRecordService.cancelById(id, login);
        if (result < 1) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, csunMessageSource
                    .getMessage("operation.failed", null));
        }

        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, csunMessageSource
                .getMessage("operation.success", null), result);
    }

    @Authorization
    @PostMapping("/add")
    public Wrapper programAdd(@CurrentUser DsmsUser login, @RequestBody DsmsRecord record){
        //根据特困人员id获取特困人员基本信息
        PoorVo dsmsPoor = dsmsPoorService.showById(record.getPoorId());
        //根据单位查询服务公司
        CompanyInfoVo dsmsCompany = dsmsCompanyService.selectByUnitId(record.getUnitId());

        DsmsRecord dsmsRecord = new DsmsRecord();
        BeanUtils.copyProperties(record,dsmsRecord);
        dsmsRecord.setPoorName(dsmsPoor.getName());
        dsmsRecord.setPoorAge(dsmsPoor.getAge());
        dsmsRecord.setPoorHeadPic(dsmsPoor.getHeadPic());
        dsmsRecord.setCompanyId(dsmsCompany.getId());
        dsmsRecord.setCompanyName(dsmsCompany.getName());
        dsmsRecord.setAreaId(dsmsCompany.getAreaId());
        dsmsRecord.setAreaName(dsmsCompany.getAreaName());
        dsmsRecord.setServiceType(1);
        Integer result = dsmsRecordService.save(dsmsRecord);

        if (result < 1) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, csunMessageSource
                    .getMessage("operation.failed", null), result);
        }

        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, csunMessageSource
                .getMessage("operation.success", null), result);
    }

    /**
     * 根据单位查询特困人员
     * @param unitId
     * @return
     */
    @Authorization
    @PostMapping("/queryPoorByUnitId")
    public Wrapper queryPoorByUnitId(Long unitId){
        DsmsPoor dsmsPoor = new DsmsPoor();
        dsmsPoor.setUnitId(unitId);
        List<DsmsPoor> select = dsmsPoorService.select(dsmsPoor);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, csunMessageSource
                .getMessage("operation.success", null), select);
    }

    /**
     * 查询临时任务
     * @return
     */
    @Authorization
    @PostMapping("/queryListByType")
    public Wrapper queryTemporaryRecord(@RequestBody RecordQueryDto recordQueryDto){

        List<DsmsRecord> dsmsRecordList = dsmsRecordService.queryListByType(recordQueryDto);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, csunMessageSource
                .getMessage("operation.success", null), new PageInfo<>(dsmsRecordList));
    }

    /**
     * 审批小程序临时任务
     * @return
     */
    @Authorization
    @PostMapping("/approvalProgramRecord")
    public Wrapper approvalTemporaryRecord(@RequestBody DsmsRecord dsmsRecord){
        DsmsRecord re = dsmsRecordService.selectByKey(dsmsRecord.getId());
        if(re.getAuditStatus() != 0){
            return WrapMapper.wrap(Wrapper.ERROR_CODE, csunMessageSource
                    .getMessage("operation.failed", null), "该任务已审核");
        }
        DsmsRecord record = new DsmsRecord();
        record.setId(dsmsRecord.getId());
        record.setAuditStatus(dsmsRecord.getAuditStatus());
        record.setReason(dsmsRecord.getReason());
        Integer result = dsmsRecordService.update(record);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, csunMessageSource
                .getMessage("operation.success", null), result);
    }

    /**
     * 评价服务
      * @param recordIdsAndEvaluation
     * @return WrapMapper
     * @author HD
     * @date  16:45
     */
    @Authorization
    @PostMapping("/approvalRecordBycompany")
    public Wrapper approvalRecordBycompany(@RequestBody RecordIdsAndEvaluation recordIdsAndEvaluation){
        if(recordIdsAndEvaluation.getIds().size() == 0){
            return WrapMapper.wrap(Wrapper.ERROR_CODE, csunMessageSource
                    .getMessage("operation.failed", null));
        }
        //判断评价的记录是否已完成
        List<DsmsRecord> dsmsRecords = dsmsRecordService.selectByRecordIds(recordIdsAndEvaluation.getIds());
        for (DsmsRecord dsmsRecord:dsmsRecords) {
            if(dsmsRecord.getStatus() != 2){
                return WrapMapper.wrap(Wrapper.ERROR_CODE, csunMessageSource
                        .getMessage("record.not.complete", null));
            }
        }
        Integer result = dsmsRecordService.approvalRecordBycompany(recordIdsAndEvaluation);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, csunMessageSource
                .getMessage("operation.success", null), result);
    }

    @PostMapping("/autoCreatedRecord")
    public Wrapper autoCreatedRecord(){
        String date = DateUtil.getNowMonth();
        Integer integer = dsmsRecordService.autoCreate(date);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, csunMessageSource
                .getMessage("operation.success", null), integer);
    }

    @GetMapping("/downLoadRecord")
    public void exportExcel(HttpServletResponse response ,@RequestParam("ids") List<Long> ids ) {
        List<DsmsRecord> dsmsRecords = dsmsRecordService.selectByRecordIds(ids);
        for (DsmsRecord d:dsmsRecords) {
            String projectName = "";
            if(d.getProjectVos().size() > 0){
                for (ProjectVo p:d.getProjectVos()) {
                    projectName = p.getProjectName() + ","+projectName;
                }
            }
            d.setProjectName(projectName);
        }
        HSSFWorkbook wb = MakeExcel(dsmsRecords);
        String fileName = "服务记录表";
        try {
            fileName = new String(fileName.getBytes("utf-8"), "ISO8859-1");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        System.out.println("fileName:" + fileName);
        response.reset();
        response.setHeader("Content-Disposition", "attachment;fileName=" + fileName + ".xls");// 指定下载的文件名
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        try {
            OutputStream output = response.getOutputStream();
            wb.write(output);
            output.flush();
            output.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private HSSFWorkbook MakeExcel(List<DsmsRecord> dsmsRecords) {
        // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        /*response.reset();
        response.setHeader("Content-Disposition", "attachment;fileName="+ fileName);// 指定下载的文件名
        OutputStream output = response.getOutputStream();
        BufferedOutputStream bufferedOutPut = new BufferedOutputStream(output);  */
        //        String path = this.getClass().getClassLoader().getResource("WEB-INF/tqjsxx").getPath();
        // 定义单元格报头
        String worksheetTitle = "服务记录";

        HSSFWorkbook wb = new HSSFWorkbook();

        // 创建单元格样式
        HSSFCellStyle cellStyleTitle = wb.createCellStyle();
        // 指定单元格居中对齐
        cellStyleTitle.setAlignment(HorizontalAlignment.CENTER);
        // 指定单元格垂直居中对齐
        cellStyleTitle.setVerticalAlignment(VerticalAlignment.CENTER);
        // 指定当单元格内容显示不下时不换行
        cellStyleTitle.setWrapText(false);
        // ------------------------------------------------------------------
        HSSFCellStyle cellStyle = wb.createCellStyle();
        // 指定单元格居中对齐
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        // 指定单元格垂直居中对齐
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        // 指定当单元格内容显示不下时换行
        cellStyle.setWrapText(true);

        // ------------------------------------------------------------------
        // 设置单元格字体
        HSSFFont font = wb.createFont();
         font.setBold(true);
        font.setFontName("宋体");
        font.setFontHeight((short) 200);
        cellStyleTitle.setFont(font);

        // 工作表名
        String staffName = "服务人员";
        String projectName = "服务项目";
        String areaName = "服务片区";
        String poorName = "特困人员姓名";
        String startServiceTime = "开始服务时间";
        String endServiceTime = "结束服务时间";
        String serviceDuration = "服务时长";

        HSSFSheet sheet = wb.createSheet();
        ExportExcel exportExcel = new ExportExcel(wb, sheet);
        // 创建报表头部
        exportExcel.createNormalHead(worksheetTitle, 11);
        // 定义第一行
        HSSFRow row1 = sheet.createRow(1);
        HSSFCell cell1 = row1.createCell(0);

        //第一行第1列
        cell1.setCellStyle(cellStyleTitle);
        cell1.setCellValue(new HSSFRichTextString(staffName));
        sheet.setColumnWidth(0, 20 * 256);;
        //第一行第2列
        cell1 = row1.createCell(1);
        cell1.setCellStyle(cellStyleTitle);
        cell1.setCellValue(new HSSFRichTextString(projectName));
        sheet.setColumnWidth(1, 20 * 256);
        //第一行第3列
        cell1 = row1.createCell(2);
        cell1.setCellStyle(cellStyleTitle);
        cell1.setCellValue(new HSSFRichTextString(areaName));
        sheet.setColumnWidth(2, 20 * 256);

        //第一行第4列
        cell1 = row1.createCell(3);
        cell1.setCellStyle(cellStyleTitle);
        cell1.setCellValue(new HSSFRichTextString(poorName));
        sheet.setColumnWidth(3, 20 * 256);

        //第一行第5列
        cell1 = row1.createCell(4);
        cell1.setCellStyle(cellStyleTitle);
        cell1.setCellValue(new HSSFRichTextString(startServiceTime));
        sheet.setColumnWidth(4, 20 * 256);
        //第一行第6列
        cell1 = row1.createCell(5);
        cell1.setCellStyle(cellStyleTitle);
        cell1.setCellValue(new HSSFRichTextString(endServiceTime));
        sheet.setColumnWidth(5, 20 * 256);
        //第一行第7列
        cell1 = row1.createCell(6);
        cell1.setCellStyle(cellStyleTitle);
        cell1.setCellValue(new HSSFRichTextString(serviceDuration));
        sheet.setColumnWidth(6, 20 * 256);


        //定义第二行开始后的实体内容
        HSSFRow row = sheet.createRow(2);
        HSSFCell cell = row.createCell(1);
        for (int i = 0; i < dsmsRecords.size(); i++) {
            DsmsRecord record = JSON.parseObject(JSONObject.toJSONString(dsmsRecords.get(i)), DsmsRecord.class);

            row = sheet.createRow(i + 2);

            cell = row.createCell(0);
            cell.setCellStyle(cellStyle);
            cell.setCellValue(new HSSFRichTextString(record.getStaffName()));

            cell = row.createCell(1);
            cell.setCellStyle(cellStyle);
            cell.setCellValue(new HSSFRichTextString(record.getProjectName()));

            cell = row.createCell(2);
            cell.setCellStyle(cellStyle);
            cell.setCellValue(new HSSFRichTextString(record.getAreaName()));

            cell = row.createCell(3);
            cell.setCellStyle(cellStyle);
            cell.setCellValue(new HSSFRichTextString(record.getPoorName()));

            cell = row.createCell(4);
            cell.setCellStyle(cellStyle);
            cell.setCellValue(new HSSFRichTextString(record.getStartServiceTime()));

            cell = row.createCell(5);
            cell.setCellStyle(cellStyle);
            //cell.setCellValue(new HSSFRichTextString(sdf.format(transactionLog.getLogTime())));
            cell.setCellValue(new HSSFRichTextString(record.getEndServiceTime()));

            cell = row.createCell(6);
            cell.setCellStyle(cellStyle);
            if(record.getServiceDuration() != null){
                cell.setCellValue(new HSSFRichTextString(record.getServiceDuration().toString()));
            }

        }
        return wb;
    }

}
